<template>
  <div>
    <el-container>
      <el-main>
        <el-row>
          <el-col :span="15">
            <el-button type="primary" @click="newselectlession">新增选课</el-button>
          </el-col>
          <el-col :span="3">
            <el-select v-model="search_type" placeholder="搜索字段">
              <el-option label="ID" value="0"></el-option>
              <!--<el-option label="用户" value="1"></el-option>-->
              <el-option label="课程" value="2"></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-input placeholder="请输入内容" v-model="searchselectlession" class="input-with-select" @input ="slessionchange">
              <el-button @click="mysearch" slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
        </el-row>
        <br>
        <el-table
          :data="tableData"
          border
          style="width: 100%">
          <!--<el-table-column type="index"></el-table-column>-->
          <el-table-column prop="course.id" label="课程ID" width="120"></el-table-column>
          <!--<el-table-column prop="user.realname" label="用户">-->
            <!--<template scope="scope">-->
              <!--<p>{{scope.row.user.id}}/{{scope.row.user.realname}}/{{scope.row.user.nickname}}/{{scope.row.user.phone}}/{{scope.row.user.email}}</p>-->
            <!--</template>-->
          <!--</el-table-column>-->
          <el-table-column prop="course.name" label="课程" width="300">
            <template scope="scope">
              <p>{{scope.row.course.name}}</p>
            </template>
          </el-table-column>
          <el-table-column prop="course.subject.name" label="课题分类" width="200">
            <template scope="scope">
              <p>{{scope.row.course.subject.name}}</p>
            </template>
          </el-table-column>
          <el-table-column prop="course.select_count" label="选课人数">
            <!--<template scope="scope">-->
              <!--<p>{{scope.row.course.id}}/<b>{{scope.row.course.name}}</b>/{{scope.row.course.subject.name}}</p>-->
            <!--</template>-->
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <!--<el-button @click="editorselectlession(scope.row)" type="text" size="small">编辑</el-button>-->
              <!--<el-button @click="deleteselectlession(scope.row)" type="text" size="small">删除</el-button>-->
              <el-button @click="coursestudents(scope.row)" type="text" size="small">选课学生</el-button>
            </template>
          </el-table-column>
        </el-table>
        <br>
        <el-row>
          <el-col :span="8"><p></p></el-col>
          <el-col :span="8">
            <el-pagination
              @current-change="currentChange"
              @size-change="sizeChange"
              background
              :page-sizes="[20, 40, 60, 100]"
              layout="sizes, prev, pager, next"
              :total="total"
              :page-size="page_size"
              :current-page="current_page"
            >
            </el-pagination>
          </el-col>
          <el-col :span="8"><p></p></el-col>
        </el-row>

        <el-dialog title="编辑选课信息" :visible.sync="dialogFormVisible" @close="dialogcolse" width="60%" center>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" :label-position="labelPosition">
              <template v-if="use === 0">
                <el-form-item label="选择用户" prop="user">
                  <el-select v-model="ruleForm.user" placeholder="请选择" style="width: 100%;" multiple>
                    <el-input placeholder="搜索用户" v-model="searchuser" class="input-with-select" @input ="userchange">
                      <el-button @click="searchusermethod" slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                    <el-option
                      v-for="item in ruleForm.users"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
              <template v-else>
                <el-form-item label="选择用户" prop="newuser">
                  <el-select v-model="ruleForm.newuser" placeholder="请选择" style="width: 100%;">
                    <el-input placeholder="搜索用户" v-model="searchuser" class="input-with-select" @input ="newuserchange">
                      <el-button @click="searchusermethod" slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                    <el-option
                      v-for="item in ruleForm.newusers"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            <el-form-item label="选择课程" prop="course">
              <el-select v-model="ruleForm.course" placeholder="请选择" style="width: 100%;">
                <el-input placeholder="搜索课程" v-model="searchuser" class="input-with-select" @input ="coursechange">
                  <el-button @click="searchcoursemethod" slot="append" icon="el-icon-search"></el-button>
                </el-input>
                <el-option
                  v-for="item in ruleForm.courses"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="resetForm('ruleForm')">取 消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
          </div>
        </el-dialog>


      </el-main>
      <el-footer></el-footer>
    </el-container>
  </div>
</template>

<script>
  import { getselectleeion, postselectleeion, patchselectleeion, deleteselectleeion, getcourse, getuser } from '@/api/course'
  export default {
    name: 'selectlessionmanager',
    data() {
      return {
        timezoneOffset: '0',
        timeoffset: '00:00:00',
        tableData: [],
        dialogFormVisible: false,
        labelPosition: 'left',
        use: 0,
        ruleForm: {
          id: 0,
          users: [],
          user: '',
          newusers: [],
          newuser: '',
          courses: [],
          course: ''
        },
        rules: {},
        searchselectlession: '',
        page_size: 20,
        total: 0,
        current_page: 1,
        searchuser: '',
        search_type: '0'
      }
    },
    methods: {
      getselectleeioninfo(page, keyword, page_size, search_type) {
        getselectleeion(page, keyword, page_size, search_type).then(response => {
          const data = response.data
          this.tableData = data
          this.total = response.data_count
        }).catch(error => {
          console.log(error)
        })
      },
      getuserinfo(page, keyword, page_size) {
        getuser(page, keyword, page_size).then(response => {
          const data = response.data
          if (data.length === 0) {
            var nal_data_list = []
            var nal_data = {}
            nal_data.value = 0
            nal_data.label = '没有搜索到数据！'
            nal_data_list.push(nal_data)
            this.ruleForm.users = nal_data_list
          } else {
            var new_data_list = []
            for (var key in data) {
              var new_data = {}
              new_data.value = data[key].id
              new_data.label = data[key].id + '/' + data[key].realname + '/' + data[key].nickname + '/' + data[key].phone + '/' + data[key].email
              new_data_list.push(new_data)
            }
            this.ruleForm.users = new_data_list
          }
        }).catch(error => {
          console.log(error)
        })
      },
      getcourseinfo(page, keyword, page_size) {
        getcourse(page, keyword, page_size).then(response => {
          const data = response.data
          if (data.length === 0) {
            var nal_data_list = []
            var nal_data = {}
            nal_data.value = 0
            nal_data.label = '没有搜索到数据！'
            nal_data_list.push(nal_data)
            this.ruleForm.courses = nal_data_list
          } else {
            var new_data_list = []
            for (var key in data) {
              var new_data = {}
              new_data.value = data[key].id
              new_data.label = data[key].id + '/' + data[key].name + '/' + data[key].subject.name + '/' + data[key].teacher.name
              new_data_list.push(new_data)
            }
            this.ruleForm.courses = new_data_list
          }
        }).catch(error => {
          console.log(error)
        })
      },
      clearFormdata() {
        this.ruleForm.id = 0
        // this.ruleForm.users = []
        this.ruleForm.user = ''
        // this.ruleForm.courses = []
        this.ruleForm.course = ''
      },
      newselectlession() {
        this.use = 0
        this.getuserinfo(1, '', 20)
        this.getcourseinfo(1, '', 20)
        var newrule = {
          user: [
            { required: true, message: '请选择用户', trigger: 'blur' }
          ],
          course: [
            { required: true, message: '请选择课程', trigger: 'blur' }
          ]
        }
        this.rules = newrule
        this.dialogFormVisible = true
      },
      editorselectlession(row) {
        this.use = 1
        //   这里出了问题
        // this.getuserinfo(1, '', 20)
        this.getcourseinfo(1, '', 20)
        // var nal_data = {}
        // nal_data.value = row.user.id
        // nal_data.label = String(row.user.id) + '/' + String(row.user.realname) + '/' + String(row.user.nickname)
        // this.ruleForm.users.unshift(nal_data)

        getuser(1, '', 20).then(response => {
          const data = response.data
          if (data.length === 0) {
            var nal_data_list = []
            var nal_data = {}
            nal_data.value = 0
            nal_data.label = '没有搜索到数据！'
            nal_data_list.push(nal_data)
            this.ruleForm.newusers = nal_data_list
          } else {
            var new_data_list = []
            for (var key in data) {
              var new_data = {}
              new_data.value = data[key].id
              new_data.label = data[key].id + '/' + data[key].realname + '/' + data[key].nickname + '/' + data[key].phone + '/' + data[key].email
              new_data_list.push(new_data)
            }
            this.ruleForm.newusers = new_data_list
          }
        }).catch(error => {
          console.log(error)
        })

        var newrule = {
          newuser: [
            { required: true, message: '请选择用户', trigger: 'blur' }
          ],
          course: [
            { required: true, message: '请选择课程', trigger: 'blur' }
          ]
        }
        this.rules = newrule
        console.log(this.ruleForm.users)
        this.ruleForm.course = row.course.id
        // this.ruleForm.user = row.user.id
        this.ruleForm.newuser = row.user.id
        this.ruleForm.id = row.id
        this.dialogFormVisible = true
      },
      mysearch() {
        this.current_page = 1
        this.getselectleeioninfo(1, this.searchselectlession, this.page_size, this.search_type)
      },
      slessionchange() {
        this.current_page = 1
        this.getselectleeioninfo(1, this.searchselectlession, this.page_size, this.search_type)
      },
      searchusermethod() {
        this.getuserinfo(1, this.searchuser, 20)
      },
      searchcoursemethod() {
        this.getcourseinfo(1, this.searchuser, 20)
      },
      userchange() {
        this.getuserinfo(1, this.searchuser, 20)
      },
      newuserchange() {
        // this.getuserinfo(1, this.searchuser)
        getuser(1, this.searchuser, 20).then(response => {
          const data = response.data
          if (data.length === 0) {
            var nal_data_list = []
            var nal_data = {}
            nal_data.value = 0
            nal_data.label = '没有搜索到数据！'
            nal_data_list.push(nal_data)
            this.ruleForm.newusers = nal_data_list
          } else {
            var new_data_list = []
            for (var key in data) {
              var new_data = {}
              new_data.value = data[key].id
              new_data.label = data[key].id + '/' + data[key].realname + '/' + data[key].nickname + '/' + data[key].phone + '/' + data[key].email
              new_data_list.push(new_data)
            }
            this.ruleForm.newusers = new_data_list
          }
        }).catch(error => {
          console.log(error)
        })
      },
      coursechange() {
        this.getcourseinfo(1, this.searchuser)
      },
      currentChange(val) {
        this.current_page = val
        console.log(this.current_page)
        this.getselectleeioninfo(this.current_page, this.searchselectlession, this.page_size)
      },
      sizeChange(val) {
        console.log(val)
        var page_count = this.total / val
        var max_pae = Math.ceil(page_count)
        this.page_size = val
        if (this.current_page <= max_pae) {
          this.getselectleeioninfo(this.current_page, this.searchselectlession, this.page_size)
        } else {
          this.getselectleeioninfo(max_pae, this.searchselectlession, this.page_size)
        }
      },
      dialogcolse() {
        // 对话框关闭的回调
        console.log('ok')
        // this.$refs['ruleForm'].resetFields()
        // this.setnall()
        this.clearFormdata() 
      },
      deleteselectlession(row) {
        this.$confirm('是否确认删除该选课, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          var id = row.id
          deleteselectleeion(id).then(response => {
            const data = response.data
            console.log(data)
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            var data_len = this.tableData.length
            var is_jump = false
            if (data_len === 1) {
              is_jump = true
            } else {
              is_jump = false
            }
            if (this.current_page === 1) {
              this.getselectleeioninfo(this.current_page, '', this.page_size)
            } else {
              if (is_jump) {
                this.getselectleeioninfo(this.current_page - 1, '', this.page_size)
              } else {
                this.getselectleeioninfo(this.current_page, '', this.page_size)
              }
            }
            // this.getselectleeioninfo(this.current_page, '', this.page_size)
          }).catch(error => {
            console.log(error)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      submitForm(formName) {
        console.log(this.ruleForm)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.ruleForm.course_id = parseInt(this.ruleForm.course)
            console.log(this.ruleForm)
            if (this.use === 1) {
              this.ruleForm.user_id = parseInt(this.ruleForm.newuser)
              patchselectleeion(this.ruleForm).then(response => {
                const data = response.data
                console.log(data)
                this.dialogFormVisible = false
                this.$message({
                  message: '修改选课成功！',
                  type: 'success'
                })
                this.getselectleeioninfo(this.current_page, '', this.page_size)
              }).catch(error => {
                console.log(error)
              })
            } else {
              this.ruleForm.user_id = parseInt(this.ruleForm.user)
              postselectleeion(this.ruleForm).then(response => {
                const data = response.data
                console.log(data)
                this.dialogFormVisible = false
                this.$message({
                  message: '新增选课成功！',
                  type: 'success'
                })
                this.getselectleeioninfo(this.current_page, '', this.page_size)
              }).catch(error => {
                console.log(error)
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      resetForm(formName) {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
        this.dialogFormVisible = false
        // this.setnall()
        this.clearFormdata()
      },
      coursestudents(row) {
        console.log(row.course.id)
        var course = row.course
        var page = this.current_page
        this.$router.push({ name: 'coursestudents', params: { course: course, page: page }})
      }
    },
    created: function() {
      var offset = new Date().getTimezoneOffset() / 60
      if (offset >= 0){
        this.timezoneOffset = '+' + offset.toString()
      } else {
        this.timezoneOffset = offset.toString()
      }
      this.timeoffset = new Date('1990-01-01 00:00:00' + this.timezoneOffset).toJSON().split('.')[0].split('T')[1] // GMT +8 为 08:00:00
      console.log(this.timezoneOffset)
      console.log(this.timeoffset)
      getselectleeion(1, '', this.page_size).then(response => {
        this.total = response.data_count
        var page = 1
        if (this.$route.params.pagenum === undefined) {
          page = 1
        } else {
          page = this.$route.params.pagenum
        }
        this.current_page = page
        console.log(page)
        this.getselectleeioninfo(this.current_page, '', this.page_size)
      }).catch(error => {
        console.log(error)
      })
      // console.log(this.$route.params.pagenum)
      // console.log(this.current_page)
      // this.getselectleeioninfo(this.current_page, '', this.page_size)
      // this.getuserinfo(1, '', 20)
      // this.getcourseinfo(1, '', 20)
    }
  }
</script>

<style scoped>

</style>
